<?php
namespace AdminModule;

use Nette\Application\UI;

/**
 * Sign in/out presenters.
 */
class DefaultPresenter extends \BasePresenter {

    public function actionDefault() {
        if ($this->user->isLoggedIn()) {
            $this->redirect('Zbozi:default');
        }
        $this->setLayout('login');
    }
    
    public function actionLogout() {
        $this->getUser()->logout();
        $this->flashMessage('Uspeěšné odhlášení.');
        $this->redirect('Default:default');
    }
    
    /**
     * Sign-in form factory.
     * @return Nette\Application\UI\Form
     */
    protected function createComponentSignInForm() {
        $form = new UI\Form;
        $form->addText('username', 'Přihlašovací jméno:')
                ->setRequired('Vložte uživatelské jméno');

        $form->addPassword('password', 'Heslo:')
                ->setRequired('Vložte heslo');

        $form->addSubmit('send', 'Přihlásit');
       
        $form->onSuccess[] = $this->signInFormSubmitted;
        return $form;
    }

    public function signInFormSubmitted($form) {
        $values = $form->getValues();

        $this->getUser()->setExpiration('+ 1 day', FALSE);

        try {
            $this->getUser()->login($values->username, $values->password);
        } catch (\Nette\Security\AuthenticationException $e) {
            $form->addError($e->getMessage());
            return;
        }

        if (isset($this->backlink)) {
            $this->restoreRequest($this->backlink);
        }
        $this->redirect('Zbozi:');
    }

}
